import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class TopK {
    //数组中前K小的值
    public static int[] topK(int[] array, int k){
        //创建一个大根堆
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        for (int i = 0; i < array.length; i++){
            //把K个数据放入堆中
            if (priorityQueue.size() < k){
                priorityQueue.offer(array[i]);
            }else {
                //开始比较
                int top = priorityQueue.peek();
                //数组元素小就放进来
                if (top > array[i]){
                    priorityQueue.poll();
                    priorityQueue.offer(array[i]);
                }
            }
        }
        int[] ans = new int[k];
        for (int i = 0; i < k; i++){
            ans[i] = priorityQueue.poll();
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] arr = {12,4,14,75,34,64};
        int[] ans = topK(arr, 3);
        System.out.println(Arrays.toString(ans));
    }
}
